package control;


import java.util.Calendar;
import java.util.LinkedList;

import model.Database;

public class OrderControl {
	private Database db;
	
	public OrderControl(){
		db = Database.getInstance();
	}
	
	public void initiateSystem(){
		db.openConnection("db34", "ekvy");
	}
	
	public void exitSystem(){
		db.closeConnection();
		System.exit(0);
	}
	
	public LinkedList<String> getCustomers(String partialCustomerName){
		LinkedList<String> list = db.getCustomers(partialCustomerName);
		list.addFirst(partialCustomerName);	
		return list;
	}
	
	public LinkedList<String> getBarcodes(String partialCustomerName) {
		LinkedList<String> list = db.getBarcodes(partialCustomerName);
		list.addFirst(partialCustomerName);	
		return list;
	}


	public void registerNewPallet(String barcode, String product) {
		db.registerNewPallet(barcode,product);
		
	}

	public void blockPallet(String barcode, boolean block, Object daysBefore) {
		db.blockPallet(barcode,block ,Integer.parseInt(((String)daysBefore)));
		
	}

	public LinkedList<String> getProducts(String partialCustomerName){
		LinkedList<String> list = db.getProducts(partialCustomerName);
		list.addFirst(partialCustomerName);	
		return list;
	}
	
	public void addError(String s){
		
	}

	public String getPalletInfo(String barcode) {
		return db.getPalletInfo(barcode);
		
	}

	public LinkedList<String> getPalletsByProduct(String product) {
		return db.getPalletInfoByProduct(product);
	}

	public void registerNewDelivery(String barcode, String customer) {
		db.registerNewDelivery(barcode, customer);
		
	}

	public LinkedList<String> getBlockedProducts() {
		return db.getBlockedProducts();
	}

	public LinkedList<String> getBlockedPalletsByProduct(String s) {
		return db.getBlockedPalletsByProduct(s);
	}

	public LinkedList<String> getCustomerDeliveryInfo(String customer) {
		return db.getProductDeliveryInfo(customer);
		
	}

	public LinkedList<String> getPalletDate(int from, int to, String year, int fromTime, int toTime) {
		return db.PalletDate(convertToMySqlDate(from, year), convertToMySqlDate(to, year), 
				convertToMySqlTime(fromTime), convertToMySqlTime(toTime));
		
	}	
	
	private String convertToMySqlTime(int time){
		if(time < 10){
			return "0"+time + ":00:00";
		}else{
			return time + ":00:00";
		}
	}
	
	private String convertToMySqlDate(int dayOfYear, String year){
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, Integer.parseInt(year));
		cal.set(Calendar.DAY_OF_YEAR, dayOfYear);
		int dayTemp = cal.get(Calendar.DATE);
		int monthTemp = cal.get(Calendar.MONTH) + 1;
		String day = convertToFormat(dayTemp);
		String month = convertToFormat(monthTemp);
		return year + "-" + month + "-" + day;
		
		
	}
	
	private String convertToFormat(int date){
		String dateTemp;
		if(date < 10){
			dateTemp = "0"+date;
		}else{
			dateTemp = Integer.toString(date);
		}
		return dateTemp;
	}
}
